<?php
namespace app\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class UserModel extends Model
{

    // 设置表名NAME="user_master";
    // 设置表名
    const TABLE_NAME = "user_master";

    protected $table = 'user_master';

    protected $primaryKey = 'user_id';

    protected $UserModel = self::TABLE_NAME;

    public $timestamps = false;

    public $user_id = "";

    public $login_id = "";

    public $password = "";

    public $user_name = "";

    public $user_kana = "";

    public $tel = "";

    public $mail = "";

    public $corp_id = "";

    public $auth = "";

    public $delete_flg = "";

    public $created_at = "";

    public $updated_at = "";

    public function readUserMaster() // 查
    {
        $sql = 'SELECT * FROM user_master where delete_flg = 0 ';
        return DB::select($sql);
        // return $this->all();
    }

    public function genNewUser()
    {
        $sql = 'SELECT max(user_id) as maxid FROM user_master where delete_flg = 0 ';
        $data = DB::select($sql);
        return "user" . str_pad($data[0]->maxid, 10, '0', STR_PAD_LEFT);
    }

    public function delUser($user_id) // 删
    {
        $sql = 'update user_master set delete_flg = 1 where user_id = ?';
        $param = [
            $user_id
        ];
        $delflag = DB::update($sql, $param);
        return $delflag;
    }

    public function updUser($data, $list, $arr) // 改
    {
        $userMaster = $this->where($list, '=', $data);
        return $userMaster->update($arr);
    }

    public function getUser($userId) // 改
    {
        $sql = 'SELECT * FROM user_master where delete_flg = 0 and user_id = ?';
        return DB::select($sql, $userId);
    }

    public function addUser($data) // 增
    {
        return $this->insert($data);
    }

    public function readCorpUserMaster($corpId) // 查
    {
        $sql = 'SELECT * FROM user_master where delete_flg = 0 and corp_id = ? ';
        $param = [
            $corpId
        ];
        return DB::select($sql, $param);
        // return $this->all();
    }

    public function getUserName($username)
    {
        $sql = 'SELECT * FROM user_master where delete_flg = 0 and user_name = ? ';
        $param = [
            $username
        ];
        return DB::select($sql, $param);
    }

    public function getUserByName($username, $userId = "")
    {
        if ($userId != null && $userId !== "") {
            $sql = 'SELECT * FROM user_master where delete_flg = 0 and user_name = ? and user_id <> ?';
            $param = [
                $username,
                $userId
            ];
            return DB::select($sql, $param);
        } else {
            $sql = 'SELECT * FROM user_master where delete_flg = 0 and user_name = ? ';
            $param = [
                $username
            ];
            return DB::select($sql, $param);
        }
    }
}
